import axios, { type AxiosRequestConfig } from 'axios'

class CancelRequest {
  pendingRequest: Map<string, AbortController> = new Map()

  private getPendingRequest(config: AxiosRequestConfig) {
    const { url, method, params, data } = config
    return [
      url,
      method,
      params ? JSON.stringify(params) : '',
      data ? JSON.stringify(data) : '',
    ].join('&')
    // 处理常见数据类型
    // const serialize = (obj: any) => {
    //   if (obj instanceof URLSearchParams) return obj.toString();
    //   if (obj instanceof FormData || obj instanceof Blob) return 'UNSERIALIZABLE_DATA';
    //   try {
    //     return JSON.stringify(obj, Object.keys(obj || {}).sort());
    //   } catch {
    //     return 'UNSERIALIZABLE_DATA';
    //   }
    // };

    // return [
    //   url,
    //   method?.toUpperCase(),
    //   params ? serialize(params) : null,
    //   data ? serialize(data) : null
    // ].filter(Boolean).join('&');
  }

  addPendingRequest(config: AxiosRequestConfig) {
    const REQUEST_KEY = this.getPendingRequest(config)
    if (this.pendingRequest.has(REQUEST_KEY)) {
      this.pendingRequest.get(REQUEST_KEY)?.abort('取消重复请求')
      this.pendingRequest.delete(REQUEST_KEY)
    }
    const controller = new AbortController()
    config.signal = controller.signal
    this.pendingRequest.set(REQUEST_KEY, controller)
  }

  removePending(config: AxiosRequestConfig) {
    const REQUEST_KEY = this.getPendingRequest(config)
    this.pendingRequest.has(REQUEST_KEY) && this.pendingRequest.delete(REQUEST_KEY)
  }

  removeAllPending() {
    for (let [key, controller] of this.pendingRequest) {
      controller.abort('取消所有pending请求')
    }
    this.pendingRequest.clear()
  }
}

export const cancelRequest = new CancelRequest()
